/*
 * bin2c.c
 *
 *  Created on: 2015年9月28日
 *      Author: yami
 */

/**
 * @file	bin2c.c
 * @author	yami
 * @date	2015年9月28日
 * @brief
 * 
 */

#include <stdio.h>
#include <stdlib.h>

char*	filenamelist[0x10]	=	{0};
char*	outCfile		=	0;
char*	outHfile		=	0;
FILE*	outH			=	0;
int		filelistsize	=	0;




int
Bin2c4file(FILE*out,FILE*bin){
	int				size;
	int				offset;
	int				i;
	int				rsize;
	unsigned char buf[0x10];
	unsigned char	*ptr;
	fseek(bin,0,SEEK_END);
	size	=	ftell(bin);
	fseek(bin,0,SEEK_SET);

	for(offset=0;offset<size;){
		rsize	=	fread(buf,1,sizeof(buf),bin);
		ptr		=	buf;
		if(rsize<0x10){
			for(i=0;i<rsize;i++){
				fprintf(out,"0x%02X,",*ptr);
				ptr++;
			}
		}
		else
		{
			for(i=0;i<4;i++){
				fprintf(out,"0x%02X,0x%02X,0x%02X,0x%02X,",
						ptr[0],ptr[1],ptr[2],ptr[3]
						);
				ptr	+=	4;
			}
		}
		fprintf(out,"\n");
		offset	+=	rsize;
	}
	return 0;
}

int
namecopy(char*dst,char*src)
{
	char	c;
	c	=	*src;
	if(c>='0'&&c<='9'){
		*dst++	=	'_';
		src	++;
	}
	while((c=*src++)){
		if(
				(c>='a'&&c<='z')
				||(c>='A'&&c<='Z')
				||(c>='0'&&c<='9')
				){
			*dst++	=	c;
		}
		else{
			*dst++	=	'_';
		}
	}
	*dst	++=	0;
	return 0;
}

int
addHFileName(const char*name){
	if(outH){
		fprintf(outH,"%s \t%s[];\n","unsigned char",name);
	}
	return 0;
}

int
Bin2c(FILE*out)
{
	int	i;
	for(i=0;i<filelistsize;i++){
		FILE	*bin;
		char*	binname;
		char	nbuf[0x100];
		binname	=	filenamelist[i];
		bin		=	fopen(binname,"rb");
		fprintf(out,"//out file %s\n",binname);
		if(bin){
			namecopy(nbuf,binname);
			addHFileName(nbuf);
			fprintf(out,"%s \t%s[]  =  \n{\n","extern unsigned char",nbuf);
			Bin2c4file(out,bin);
			fprintf(out,"\n};\n");
		}
	}
	return 0;
}





int
addFileName(const char*n){
	if(filelistsize>=0x10)
		return 1;
	filenamelist[filelistsize++]	=	(char*)n;
	return 0;
}

int
checkProgram(){
	if(filelistsize==0){
		return 1;
	}
	return 0;
}

int
main(int argc,char**argv)
{
	int		i;
	if(argc<=1){
		printf("error no input file");
		return 1;
	}
	for(i=1;i<argc;i++){

		if(argv[i][0]!='-'){
			if(addFileName(argv[i])){
				return 1;
			}
		}
		else{
			if(argv[i][1] == 'o'){
				if(argv[i][2] == '\0'){
					outCfile	=	argv[i+1];
					i++;
				}
				else{
					outCfile	=	argv[i] + 2;
				}
			}
			else if(argv[i][1] == 'h'){
				if(argv[i][2] == '\0'){
					outHfile	=	argv[i+1];
					i++;
				}
				else{
					outHfile	=	argv[i] + 2;
				}
			}
		}
	}



	if(checkProgram()){
		return 1;
	}

	printf("//out file");

	if(outHfile){
		outH	=	fopen(outHfile,"w+");
	}
	if(outCfile){
		FILE*	out;
		out	=	fopen(outCfile,"w+");
		if(out){
			int	r;
			r	=	Bin2c(out);
			fclose(out);
			return r;
		}
		else
			return 1;
	}
	else{
		Bin2c(stdout);
	}
	return 0;
}


